//
//  MGSettingController.m
//  MoneyGoal_iOS
//
//  Created by yyb on 2022/7/28.
//  Copyright © 2022 Moneyease CO,. LTD. All rights reserved.
//

#import "MGSettingController.h"
#import "MGSettingDataController.h"
#import "MGProfileController.h"
#import "MGSettingConfigController.h"
#import "MGLoginController.h"

#import "MGNotLoginView.h"
#import "MGSettingUserView.h"
#import "MGSettingSheetView.h"

#import "MGActivityItem.h"

#import "MGSettingCell.h"
#import "MGSettingSectionCell.h"

//#import "WXApi.h"

@interface MGSettingController ()<ASAuthorizationControllerDelegate>
@property (nonatomic, strong) MGNotLoginView *headerView;
@property (nonatomic, strong) MGSettingUserView *userHeaderView;
@property (nonatomic, strong) MGSettingSheetView *userSheetView;

@end

@implementation MGSettingController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isHiddenNavigationReturnButton = YES;
}

- (void)afterConfigViewAction {
    [super afterConfigViewAction];
    
    self.headerView = [[MGNotLoginView alloc] init];
    self.headerView.frame = CGRectMake(0, 0, kScreenWidth, 100);
    
    @weakify(self);
    self.headerView.doLoginBlock = ^{
        [YYBViewRouter openOnClass:[MGLoginController class]];
    };
    
    // ==============================
    self.userHeaderView = [[MGSettingUserView alloc] init];
    self.userHeaderView.frame = CGRectMake(0, 0, kScreenWidth, 160);
    self.userHeaderView.tapedActionBlock = ^{
        [YYBViewRouter openOnClass:[MGProfileController class]];
    };
    
    // ==============================
    self.userSheetView = [[MGSettingSheetView alloc] init];
    self.userSheetView.frame = CGRectMake(0, 0, kScreenWidth, 95);
    self.userSheetView.tapedActionBlock = ^{
        @strongify(self);
        [self _handleLogout];
    };
}

- (void)beginCreateNotifications {
    @weakify(self);
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:YYBUserLoginNotifictaion object:nil]
     subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        [self _handleUserStatus];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:YYBUserLogoutNotifictaion object:nil]
     subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        [self _handleUserStatus];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:YYBUserUpdateNotifictaion object:nil]
     subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        [self _handleUserStatus];
    }];
}

- (void)beginQueryData {
    [super beginQueryData];
    
    [self _handleUserStatus];
}

- (void)_handleLogout {
    [MGAlertView showAlertViewWithTitle:nil detail:@"确定退出当前账号吗？" firstActionTitle:@"取消" firstActionTapedBlock:nil secondActionTitle:@"确定" secondActionTapedBlock:^{
        [MGCommonAccessor.shared clearAllLocalData:^{
            [MGUserModel doUserLogout];
        } errorBlock:^(NSError *error) {
            
        }];
    }];
}

- (void)_handleUserStatus {
    [self.tableView reloadData];
    
    if ([MGUserModel isUserLogin]) {
        self.tableView.tableHeaderView = self.userHeaderView;
        self.tableView.tableFooterView = self.userSheetView;
        [self.userHeaderView configViewWithDataModel:[MGUserModel user]];
    } else {
        self.tableView.tableHeaderView = self.headerView;
        self.tableView.tableFooterView = nil;
    }
}

- (NSArray<NSString *> *)dequeueCellIdentifiers {
    return @[@"MGSettingCell", @"MGSettingSectionCell"];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 5;
    } else if (section == 1) {
        return 2;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 10;
    }
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        MGSettingSectionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGSettingSectionCell"];
        return cell;
    }
    
    MGSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGSettingCell"];
    cell.backgroundColor = [UIColor whiteColor];
    
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            [cell configViewWithTitleValue:@"问题交流" icon:@"setting_zone" hidesWhenLogin:YES];
        } else if (indexPath.row == 2) {
            [cell configViewWithTitleValue:@"五星好评" icon:@"setting_star" hidesWhenLogin:YES];
        } else if (indexPath.row == 3) {
            [cell configViewWithTitleValue:@"推荐给他人" icon:@"setting_share" hidesWhenLogin:YES];
        } else if (indexPath.row == 4) {
            [cell configViewWithTitleValue:@"应用设置" icon:@"setting_config" hidesWhenLogin:YES];
        }
    } else if (indexPath.section == 1) {
        if (indexPath.row == 1) {
            // 未登录时，需要提醒登录才能用这个功能
            [cell configViewWithTitleValue:@"数据" icon:@"setting_data" hidesWhenLogin:[MGUserModel isUserLogin]];
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            NSString *urlStr = [NSString stringWithFormat:@"mqqapi://card/show_pslcard?src_type=internal&version=1&uin=%@&key=%@&card_type=group&source=external&jump_from=webapi", @"747899160",@"075424f4e98967ce49961d1f070287bc734eb9428205c94a0e49083953b6a074"];
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr] options:nil completionHandler:^(BOOL success) {
                if (!success) {
                    [YYBAlertView showAlertViewWithStatusString:@"暂无法跳转页面"];
                }
            }];
        } else if (indexPath.row == 2) {
            NSString *appleStoreURL = @"itms-apps://itunes.apple.com/app/id1625069207?action=write-review";
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appleStoreURL] options:nil completionHandler:^(BOOL success) {
                if (!success) {
                    [YYBAlertView showAlertViewWithStatusString:@"暂无法跳转页面"];
                }
            }];
        } else if (indexPath.row == 3) {
            MGActivityItem *activityItem = [MGActivityItem activityItemSourceUrlWithIcon:[UIImage imageNamed:@"logo_mini"]];
            NSString *name = [NSBundle mainBundle].infoDictionary[@"CFBundleDisplayName"];
            name = [NSString stringWithFormat:@"%@-多多快乐生活", name];
            NSString *appPath = @"https://itunes.apple.com/us/app/fa-bu-ce-shi/id1491424390?l=zh&ls=1&mt=8";

            UIActivityViewController *vc = [[UIActivityViewController alloc] initWithActivityItems:@[activityItem, name, [NSURL URLWithString:appPath]] applicationActivities:nil];
            [self presentViewController:vc animated:YES completion:nil];
        } else if (indexPath.row == 4) {
            [YYBViewRouter openOnClass:[MGSettingConfigController class]];
        }
    } else if (indexPath.section == 1) {
        if ([MGUserModel isUserLogin]) {
            if (indexPath.row == 1) {
                [YYBViewRouter openOnClass:[MGSettingDataController class]];
            }
        }
    }
}

- (NSString *)customPageTitle {
    return @"设置";
}

- (BOOL)hidesBottomBarWhenPushed {
    return NO;
}

@end
